package com.xugongzhang.service;

import com.xugongzhang.dto.Message;
import com.xugongzhang.enums.MessageTypeEnum;
import com.xugongzhang.thread.ManageServerConnectClientThread;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Date;
import java.util.Scanner;

/**
 * @author X
 * @date 2022/11/28 10:14
 * 给所有人推送消息
 */
public class SendNewsToAllService implements Runnable {
    
    private Scanner scanner = new Scanner(System.in);
    
    @Override
    public void run() {

        // 为了可以多次推送消息，所以循环

        while (true) {
            System.out.print("请输入服务器要推送的新闻（exit表示退出推送服务）：");
            String news = scanner.next();
            if ("exit".equals(news)) {
                break;
            }
            Message message = new Message();
            message.setMsgType(MessageTypeEnum.TO_ALL_MSG.getMessageType());
            message.setSender("服务器");
            message.setContent(news);
            message.setSendTime(new Date().toString());
            System.out.println("服务器对所有人说：" + news);
            ManageServerConnectClientThread.getMap().keySet().stream()
                    .map(item -> ManageServerConnectClientThread.getServerConnectClientThread(item).getSocket())
                    .forEach(socket -> {
                        try {
                            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                            oos.writeObject(message);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
        }

    }
}
